package com.kmzx.one.project.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.kmzx.one.common.utils.UUIDGenerator;
import com.kmzx.one.project.entity.ProductSource;
import com.kmzx.one.project.entity.SourceUserDown;
import com.kmzx.one.project.entity.SourceUserStore;
import com.kmzx.one.project.mapper.CustomerMapper;
import com.kmzx.one.project.mapper.MaterialMapper;
import com.kmzx.one.project.mapper.ProductMapper;
import com.kmzx.one.project.others.common.IdAndTitle;
import com.kmzx.one.project.others.dso.ProdJoinAttributeWithCategory;
import com.kmzx.one.project.others.dso.ProdJoinDiscount;
import com.kmzx.one.project.others.dto.MateCateOutInfo;
import com.kmzx.one.project.others.dto.MateOutInfo;
import com.kmzx.one.project.others.dto.MaterialDetailInfo;
import com.kmzx.one.project.others.dto.MemberActionInfo;
import com.kmzx.one.project.others.dto.PagedMateOutInfo;
import com.kmzx.one.project.others.dto.UserMateOutInfo;
import com.kmzx.one.project.service.MaterialService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class MaterialServiceImpl implements MaterialService {
    private static final Logger logger = LoggerFactory.getLogger(MaterialServiceImpl.class);
    @Autowired
    MaterialMapper materialMapper;


    @Autowired
    private CustomerMapper customerMapper;


    @Autowired
    private ProductMapper productMapper;


    @Override
    public List<MateCateOutInfo> findAllMaterialCategory(String userId) throws Exception {
        MateCateOutInfo outInfo = new MateCateOutInfo();
        outInfo.setCateId("__all__").setCateName("全部").setSeria(-2);
        List<MateCateOutInfo> infos = materialMapper.selectAllMateCateInfo();
        if (infos != null) {
            infos.add(outInfo);
            infos.sort(Comparator.comparing(MateCateOutInfo::getSeria));
            return infos;
        } else {
            ArrayList<MateCateOutInfo> outInfos = new ArrayList<>();
            outInfos.add(outInfo);
            return outInfos;
        }
    }

    @Override
    public PagedMateOutInfo findAllMaterialById(String cateId, Integer pageNum, Integer pageSize, String userId) throws Exception {
        //查找全部
        PagedMateOutInfo mate;
        if (cateId != null && "__all__".equals(cateId)) {
            PageHelper.startPage(pageNum, pageSize, true);
            Page<MateOutInfo> pe = materialMapper.findAllMaterial(pageNum, pageSize);
            mate = new PagedMateOutInfo(pe.getPageNum(), pe.getPageSize(), pe.getStartRow(), pe.getEndRow(), pe.getTotal(), pe.getPages());
            mate.setChildren(pe.getResult());

        } else {
            PageHelper.startPage(pageNum, pageSize, true);
            Page<MateOutInfo> pe = materialMapper.findAllMaterialById(cateId, pageNum, pageSize);
            mate = new PagedMateOutInfo(pe.getPageNum(), pe.getPageSize(), pe.getStartRow(), pe.getEndRow(), pe.getTotal(), pe.getPages());
            mate.setChildren(pe.getResult());

        }
        List<MateOutInfo> result = mate.getChildren();
        if (result != null && result.size() > 0) {
            List<String> mateIdList = result.stream().filter(mo -> mo.getKinds() == 1).map(ll -> ll.getMateId()).collect(Collectors.toList());
            if (mateIdList != null && mateIdList.size() > 0) {
                List<IdAndTitle> titles = materialMapper.selectMateVideoUrl(mateIdList);
                for (MateOutInfo info : result) {
                    String pic = info.getMateOssUrl();
                    int dot = pic.lastIndexOf(".");
                    int subLine = pic.lastIndexOf("_");
                    String[] xes = pic.substring(subLine + 1, dot).split("×");
                    info.setWidth(Integer.valueOf(xes[0]));
                    info.setHeight(Integer.valueOf(xes[1]));


                    for (IdAndTitle title : titles) {
                        if (info.getMateId().equals(title.getId())) {
                            info.setVideoUrl(title.getTitle());
                        }
                    }
                }
            }
        }
        mate.setChildren(result);
        return mate;
    }

    @Override
    public MaterialDetailInfo findAllMaterialDetail(String mateId, String userId) throws Exception {
        List<MaterialDetailInfo> detail = materialMapper.findAllMaterialDetail(mateId, userId);
        if (detail != null && detail.size() > 0) {
            List<String> list = detail.stream().map(md -> md.getPicUrl()).collect(Collectors.toList());
            MaterialDetailInfo info = detail.get(0);
            int cate = info.getOssKinds();
            info.setCarouselsImg(list);
            if (cate == 1) {
                String pic = list.get(0);
                int dot = pic.lastIndexOf(".");
                int subLine = pic.lastIndexOf("_");
                String[] xes = pic.substring(subLine + 1, dot).split("×");
                info.setWidth(Integer.valueOf(xes[0]));
                info.setHeight(Integer.valueOf(xes[1]));
                List<String> subList = list.subList(1, list.size());
                info.setCarouselsImg(subList);
            } else {
                String picUrl = info.getPicUrl();
                int subLine = picUrl.lastIndexOf("_");
                int dot = picUrl.lastIndexOf(".");
                String[] xes = picUrl.substring(subLine + 1, dot).split("×");
                info.setWidth(Integer.valueOf(xes[0]));
                info.setHeight(Integer.valueOf(xes[1]));


            }
            String prodId = info.getProdId();

            boolean has = false;
            List<String> specUsers = customerMapper.findSpecificUser();

            if (!CollectionUtils.isEmpty(specUsers) && (userId != null && userId != "")) {

                if (specUsers.contains(userId)) {
                    // 有特权,有用户,也是
                    has = true;
                } else { // 有特权,有用户,但不是
                    has = false;
                }
            } else {
                // 没特权,没用户
                // 有特权,没用户
                has = false;
            }


            List<ProdJoinAttributeWithCategory> joinAttributes = productMapper.selectProdEntryInfo2(prodId);
            BigDecimal minPrice = productMapper.findProductSpecificMinPrice(prodId);
            // 所有的商品打折活动,包括所有的商品
            List<ProdJoinDiscount> discounts = productMapper.selectProductJoinDiscount(prodId);
            if (!CollectionUtils.isEmpty(joinAttributes)) {
                ProdJoinAttributeWithCategory joinAttribute = joinAttributes.get(0);

                info.setEnabled(joinAttribute.getStates());
                Integer inOrOut = joinAttribute.getInOrOut();
                info.setInOrOut(inOrOut);
                info.setProdPrice(joinAttributes.stream().sorted(Comparator.comparing(ProdJoinAttributeWithCategory::getPrice)).findFirst().get().getPrice());
                info.setCurrentPrice(info.getProdPrice());
                info.setBeauty(info.getCurrentPrice());

                if (discounts != null && discounts.size() > 0) {
                    Map<String, List<ProdJoinDiscount>> listMap = discounts.stream().collect(Collectors.groupingBy(ProdJoinDiscount::getProductId));
                    List<ProdJoinDiscount> discountList = listMap.get(prodId);
                    if (discountList != null && discountList.size() > 0) {
                        ProdJoinDiscount discount = discountList.get(0);

                        // 固定折扣
                        info.setKinds(1);
                        BigDecimal currentPrice = info.getCurrentPrice();
                        info.setDiscountImg(discount.getDiscountImg());
                        if (discount.getDiscountCate() == 0) {
                            if(discount.getDiscountNum().compareTo(BigDecimal.ONE)==0){
                                info.setKinds(0);
                            }
                            info.setCurrentPrice(currentPrice.multiply(discount.getDiscountNum()));
                        } else {
                            info.setCurrentPrice(discount.getDiscountNum());
                        }
                        info.setBeauty(info.getCurrentPrice());
                    }
                }

                if (has && minPrice != null) {
                    // 特权的最小价格
                    info.setCurrentPrice(minPrice);
                    info.setProdPrice(minPrice);
                    info.setBeauty(minPrice);
                } else {
                    // 直升商品
                    List<MemberActionInfo> actionInfos = productMapper.selectProductStraight();
                    if (!CollectionUtils.isEmpty(actionInfos)) {
                        List<Map<String, Object>> lists = productMapper.selectProdFastKind(prodId, 0);

                        if (!CollectionUtils.isEmpty(lists)) {
                            for (Map<String, Object> objectMap : lists) {
                                Double growthValue = (Double) objectMap.get("growthValue");
                                info.setBeauty(BigDecimal.valueOf(growthValue));
                                BigDecimal upMoney = (BigDecimal) objectMap.get("upMoney");
                                info.setCurrentPrice(upMoney);
                                info.setKinds(2);
                                info.setFastIcon((String) objectMap.get("picOne"));
                                info.setBeauty(info.getCurrentPrice());
                            }
                        }
                    }
                }
                Map<String, BigDecimal> freeFee = productMapper.selectProductFreeFee();
                Integer po = productMapper.selectProdAttributeStoreId3(prodId);
                if (po != null && po != 0) {
                    info.setHas(true);
                }

            }

            // 收藏
            List<SourceUserStore> storeList = materialMapper.selectSourceStore(mateId);
            if (storeList == null) {
                info.setStoreNum(0);
                info.setStore(false);
            } else {
                info.setStoreNum(storeList.size());
                if (userId != null && !"".equals(userId)) {
                    long count = storeList.stream().filter(ob -> ob.getUserId().equals(userId)).count();
                    if (count > 0) {
                        info.setStore(true);
                    }
                }
            }
            return info;
        }
        return null;
    }

    @Override
    public UserMateOutInfo findUserMaterialStore(String userId, Integer pageNum, Integer pageSize) {
        Page<Object> objects = PageHelper.startPage(pageNum, pageSize, true);
        Page<MateOutInfo> pe = materialMapper.findUserMaterial(userId);
        UserMateOutInfo outInfo = new UserMateOutInfo(pe.getPageNum(), pe.getPageSize(), pe.getStartRow(), pe.getEndRow(), pe.getTotal(), pe.getPages());
        List<MateOutInfo> result = pe.getResult();
        if (result != null && result.size() > 0) {
            List<String> mateIdList = result.stream().filter(mo -> mo.getKinds() == 1).map(ll -> ll.getMateId()).collect(Collectors.toList());
            if (mateIdList != null && mateIdList.size() > 0) {
                List<IdAndTitle> titles = materialMapper.selectMateVideoUrl(mateIdList);
                for (MateOutInfo info : result) {
                    String pic = info.getMateOssUrl();
                    int subLine = pic.lastIndexOf("_");
                    int dot = pic.lastIndexOf(".");
                    String[] xes = pic.substring(subLine + 1, dot).split("×");
                    info.setHeight(Integer.valueOf(xes[1]));
                    info.setWidth(Integer.valueOf(xes[0]));

                    for (IdAndTitle title : titles) {
                        if (info.getMateId().equals(title.getId())) {
                            info.setVideoUrl(title.getTitle());
                        }
                    }
                }
            }
        }

        outInfo.setChildren(result);
        outInfo.setUserId(userId);
        return outInfo;
    }

    @Override
    public int doUserMaterialStore(String mateId, String userId) {
        List<SourceUserStore> stores = materialMapper.selectSourceUserStore(userId, mateId);
        if (stores != null && stores.size() > 0) {
            SourceUserStore store = stores.get(0);
            if (store.getStates() == 1) {
                store.setStates(0).setDeleted(1);
                Date updateTime = new Date();
                store.setUpdateTime(updateTime);
                logger.info("取消收藏素材");
                materialMapper.updateSourceStoreById(store);
                materialMapper.storeMaterial(mateId, 2);
                logger.info("取消收藏素材OK");
            }
        } else {
            ProductSource source = materialMapper.selectProductSourceById(mateId);
            Date updateTime = new Date();
            SourceUserStore sourceUserStore = new SourceUserStore();
            sourceUserStore.setId(UUIDGenerator.generate()).setUserId(userId).setProductSourceId(mateId)
                    .setDeleted(0).setStates(1).setCreateTime(updateTime).setUpdateTime(updateTime);
            sourceUserStore.setIsChange(source.getIsChange()).setProductId(source.getProductId());

            logger.info("新增收藏素材");
            materialMapper.insertUserMaterialStore(sourceUserStore);
            materialMapper.storeMaterial(mateId, 1);
            logger.info("新增收藏素材OK");
        }

        return 0;
    }

    @Override
    public int downloadMaterial(String mateId, String userId) {
        if (userId == null || "".equals(userId)) {
            logger.info("新增下载素材");
        } else {
            SourceUserDown down = new SourceUserDown();
            down.setId(UUIDGenerator.generate()).setCreateTime(new Date()).setUpdateTime(new Date())
                    .setProductSourceId(mateId).setStates(1).setUserId(userId);
            ProductSource source = materialMapper.selectProductSourceById(mateId);
            down.setProductId(source.getProductId());
            logger.info("新增下载素材");
            materialMapper.insertUserMaterialDown(down);
            materialMapper.downloadMaterial(mateId, 1);
            logger.info("新增下载素材OK");
        }
        return 0;
    }


}
